package br.rfpm.web;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.rfpm.dominio.Authority;
import br.rfpm.dominio.Usuario;
import br.rfpm.dominio.service.AuthorityService;
import br.rfpm.dominio.service.UsuarioService;
import br.rfpm.util.Mensagem;
import br.rfpm.web.util.MD5;

@RequestMapping("/")
public class AutenticacaoController implements Serializable, AuthenticationProvider {
	
	private static final long serialVersionUID = 1767137050540682793L;

	@Autowired
	private UsuarioService usuarioService;
	
	@Autowired
	private AuthorityService authorityService;
	
	private Usuario usuario;

	@RequestMapping(method = RequestMethod.GET)
	public String index(HttpSession session, Model model) {
		if (session.getAttribute("usuario") != null) {
			return "redirect:/homeController";
		}
		model.addAttribute(Mensagem.INFOMACAO, "Necessário fazer o login");
		return "index";
	}

	@RequestMapping(value = "autenticar",method = RequestMethod.GET)
	public String autenticar() {
		return "index";
	}
	
	@RequestMapping(value = "autenticar", method = RequestMethod.POST)
	public String autenticar(String login, String password, HttpSession session, Model model) {
		try {
			this.usuario = this.usuarioService.autenticarUsuario(login, password);
			SecurityContextHolder.getContext().setAuthentication(this.usuario);
			session.setAttribute("usuario", this.usuario);
			return "redirect:/homeController";
		} catch (Exception e) {
			model.addAttribute(Mensagem.ERRO, e.getMessage());
		}
		return "index";
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		return authentication;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean supports(Class authentication) {
		return authentication.isAssignableFrom(Usuario.class);
	}
	
	@RequestMapping(value="sair", method=RequestMethod.GET)
	public String sair(HttpSession session) {
		session.removeAttribute("usuario");
		session.invalidate();
		SecurityContextHolder.clearContext();
		return "index";
	}
	
	public void inserirUsuario(Model model) {
		
		try {
			
			Usuario usuario = this.usuarioService.consultaUsuarioPorLogin("pugliese");
			
			if (usuario == null) {
				usuario = new Usuario();
				usuario.setCredentials(MD5.criptografar("thassio"));
				usuario.setLogin("pugliese");
				usuario.setName("Rafael Fernandes Pugliese de Morais");
				usuario = this.usuarioService.inserir(usuario);
			}
			
			if (usuario.getAuthorities() == null || (usuario.getAuthorities() != null && usuario.getAuthorities().isEmpty())) {
				List<Authority> authorities = this.authorityService.listarPorAuthority(Authority.ROLE_USER);
				Authority authority = new Authority(Authority.ROLE_USER);
				if (authorities.isEmpty()) {
					authority = this.authorityService.inserir(authority);
					usuario.addAuthority(authority);
				} else {
					usuario.addAllAuthority(authorities);
				}
				this.usuarioService.alterar(usuario);
			}
			
		} catch (NoSuchAlgorithmException e) {
			model.addAttribute(Mensagem.ERRO, e.getMessage());
		}
		
	}

}
